﻿using System;
using System.Drawing.Imaging;
using System.Drawing.Drawing2D;
using System.Drawing;
using System.Runtime.InteropServices;
using System.IO;
using System.Text;
using Telerik.Web.UI;
using Telerik.Web.UI.Upload;
using Guru.Web.Controls.Validators;
using System.Linq;
using Guru.Web.UI;

public partial class UM_CreateTheme : HSMPage
{
    #region constant
    protected const string TEMPALTE_PATH = "~/App_Data/ThemeTemplate/Default";
    protected const string THEME_LIST_PATH = "~/App_Data/ThemeInformation.xml";
    protected const string THEME_PATH = "~/App_Themes/{0}";
    protected const string THEME_NAME_DEFAULT_FOR_CREATE = "{0}_DefaultForCreate";
    
    /// <summary>
    /// Max image size in KB
    /// </summary>
    protected const int MAX_IMAGE_SIZE = 500;
    #endregion

    protected enum PostBackAction 
    {
        Submit,
        LoadDefaultForCreate,
        ChangeMode,
        ChangeThemeName

    }
    protected enum DataBindAction
    {
        LoadDefaultForCreate,
        BindValidateItem
    }
   

    protected bool IsUpdateMode
    {
        get 
        {
            return this.uxRadioEdit.Checked;
        }
    }
    protected TaxThemeInfoCollection ThemeList
    {
        get
        {

            string xmlFilePath = Server.MapPath(THEME_LIST_PATH);
            string xmlThemes = TaxIOExtensions.ReadTextFile(xmlFilePath).ToString();
            TaxThemeInfoCollection themeList = null;
            if (string.IsNullOrEmpty(xmlThemes))
            {
                themeList = new TaxThemeInfoCollection();
            }
            else
            {
                themeList = (TaxThemeInfoCollection)HSMCommon.ConvertXMLToObject(xmlThemes, typeof(TaxThemeInfoCollection));
            }
            return themeList;
        }
    }
    protected TaxThemeInfoCollection CurrentThemeList
    {
        get
        {
            string xmlFilePath = Server.MapPath(THEME_LIST_PATH);
            string xmlThemes = TaxIOExtensions.ReadTextFile(xmlFilePath).ToString();
            TaxThemeInfoCollection currentThemeList = new TaxThemeInfoCollection(); ;
            TaxThemeInfoCollection themeList = new TaxThemeInfoCollection();
            if (!string.IsNullOrEmpty(xmlThemes))          
            {
                themeList = (TaxThemeInfoCollection)HSMCommon.ConvertXMLToObject(xmlThemes, typeof(TaxThemeInfoCollection));
            }

            foreach (TaxThemeInformation t in themeList)
            {
                if (string.IsNullOrEmpty(t.CreatedClientID) || int.Parse(t.CreatedClientID) == HSMSessionManager.CurrentClientID)
                {
                    currentThemeList.Add(t);
                }
            }
            if (currentThemeList != null)
            {
                currentThemeList.Sort();
            }
           
            return currentThemeList;
        }
    }
    protected TaxThemeInformation CurrentEditTheme
    {
        get 
        {
            TaxThemeInformation theme = new TaxThemeInformation();
            if (this.IsUpdateMode)
            {
                theme.ThemeName = this.uxThemeList.SelectedValue.Trim();
            }
            else
            {
                theme.ThemeName = this.uxThemeName.Text.Trim();
            }

            theme.BackgroundColor = this.uxBackgroundColor.SelectedColor.ToHtml();
            theme.DefaultTextColor = this.uxPrimaryTextColor.SelectedColor.ToHtml();
            theme.PrimaryColor = this.uxPrimaryColor.SelectedColor.ToHtml();
            theme.PrimaryLinkColor = this.uxPrimaryLinkColor.SelectedColor.ToHtml();

            theme.RightHeaderBackgroundColor = this.uxRightHeaderBackgroundColor.SelectedColor.ToHtml();
            theme.LeftHeaderBackgroundColor = this.uxLeftHeaderBackgroundColor.SelectedColor.ToHtml();
            theme.HeaderTextColor = this.uxHeaderTextColor.SelectedColor.ToHtml();

            theme.MenuTextColor = this.uxMenuTextColor.SelectedColor.ToHtml();

            theme.BorderColor = this.uxBorderColor.SelectedColor.ToHtml();
            theme.ExportBackgroundColor = this.uxExportBackgroundColor.SelectedColor.ToHtml();
            theme.ExportTextColor = this.uxExportTextColor.SelectedColor.ToHtml();

            theme.GridAlterRowColor = this.uxGridAlterRowColor.SelectedColor.ToHtml();
            theme.GridHeaderTextColor = this.uxGridHeaderTextColor.SelectedColor.ToHtml();
            theme.GridLineBorderColor = this.uxGridLineBorderColor.SelectedColor.ToHtml();
            theme.ReportTotalBackgroundColor = this.uxReportTotalBackgroundColor.SelectedColor.ToHtml();
            theme.ReportTotalTextColor = this.uxReportTotalTextColor.SelectedColor.ToHtml();

            theme.ButtonTextColor = this.uxButtonTextColor.SelectedColor.ToHtml();
            theme.ButtonColor = this.uxButtonColor.SelectedColor.ToHtml();
            theme.ButtonSecondaryColor = this.uxButtonSecondaryColor.SelectedColor.ToHtml();

            theme.LoginAddrBackgroundColor = this.uxLoginAddrBackgroundColor.SelectedColor.ToHtml();
            theme.LoginAddrTextColor = this.uxLoginAddrTextColor.SelectedColor.ToHtml();
            theme.CreatedUser = HSMSessionManager.CurrentUser.UserFullName;
            theme.CreatedClientID = HSMSessionManager.CurrentClientID.ToString();
            theme.CreatedDate = DateTime.Now;
            
            return theme;
        }
        set 
        {
            TaxThemeInformation theme = value;
            this.uxBackgroundColor.SelectedColor = ColorTranslator.FromHtml(theme.BackgroundColor);
            this.uxPrimaryTextColor.SelectedColor = ColorTranslator.FromHtml(theme.DefaultTextColor);
            this.uxPrimaryColor.SelectedColor = ColorTranslator.FromHtml(theme.PrimaryColor);
            this.uxPrimaryLinkColor.SelectedColor = ColorTranslator.FromHtml(theme.PrimaryLinkColor);

            this.uxRightHeaderBackgroundColor.SelectedColor = ColorTranslator.FromHtml(theme.RightHeaderBackgroundColor);
            this.uxLeftHeaderBackgroundColor.SelectedColor = ColorTranslator.FromHtml(theme.LeftHeaderBackgroundColor);
            this.uxHeaderTextColor.SelectedColor = ColorTranslator.FromHtml(theme.HeaderTextColor);

            this.uxMenuTextColor.SelectedColor = ColorTranslator.FromHtml(theme.MenuTextColor);

            this.uxBorderColor.SelectedColor = ColorTranslator.FromHtml(theme.BorderColor);
            this.uxExportBackgroundColor.SelectedColor = ColorTranslator.FromHtml(theme.ExportBackgroundColor);
            this.uxExportTextColor.SelectedColor = ColorTranslator.FromHtml(theme.ExportTextColor);

            this.uxGridAlterRowColor.SelectedColor = ColorTranslator.FromHtml(theme.GridAlterRowColor);
            this.uxGridHeaderTextColor.SelectedColor = ColorTranslator.FromHtml(theme.GridHeaderTextColor);
            this.uxGridLineBorderColor.SelectedColor = ColorTranslator.FromHtml(theme.GridLineBorderColor);
            this.uxReportTotalBackgroundColor.SelectedColor = ColorTranslator.FromHtml(theme.ReportTotalBackgroundColor);
            this.uxReportTotalTextColor.SelectedColor = ColorTranslator.FromHtml(theme.ReportTotalTextColor);

            this.uxButtonTextColor.SelectedColor = ColorTranslator.FromHtml(theme.ButtonTextColor);
            this.uxButtonColor.SelectedColor = ColorTranslator.FromHtml(theme.ButtonColor);
            this.uxButtonSecondaryColor.SelectedColor = ColorTranslator.FromHtml(theme.ButtonSecondaryColor);

            this.uxLoginAddrBackgroundColor.SelectedColor = ColorTranslator.FromHtml(theme.LoginAddrBackgroundColor);
            this.uxLoginAddrTextColor.SelectedColor = ColorTranslator.FromHtml(theme.LoginAddrTextColor);
        }
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            OnDataBindControls(DataBindAction.LoadDefaultForCreate, sender);           
        }
      
        OnDataBindControls(DataBindAction.BindValidateItem, sender);
       
    }   

    protected void OnPostBackActions(Enum type, object sender)
    {
       
        switch ((PostBackAction)type)
        {
            case PostBackAction.Submit:
                bool isValid = this.Validate();
                if (!isValid) return;

                TaxThemeInformation theme = this.CurrentEditTheme;
                if (this.uxLogoImage.UploadedFiles.Count > 0)
                {
                    theme.Logo = Image.FromStream(this.uxLogoImage.UploadedFiles[0].InputStream);
                }
                else if (this.IsUpdateMode)
                {
                    string logoPath = Server.MapPath(string.Format(THEME_PATH, theme.ThemeName + "/Images/aperia-md-color.png"));
                    theme.Logo = GraphicExtension.ReadFromFile(logoPath);
                }

                if (this.uxBackgroundImage.UploadedFiles.Count > 0)
                {
                    theme.BackgroundImage = Image.FromStream(this.uxBackgroundImage.UploadedFiles[0].InputStream);
                }
                else if (this.IsUpdateMode)
                {
                    string backPath = Server.MapPath(string.Format(THEME_PATH, theme.ThemeName + "/Images/dot.png"));
                    theme.BackgroundImage = GraphicExtension.ReadFromFile(backPath);
                }

                theme.IsUpdateMode = this.IsUpdateMode;

                if (this.uxChkGenerate.Checked)
                    this.GenerateTheme(theme);

                if (this.uxChkSaveTheme.Checked)
                    this.SaveThemeInfomation(theme);

                if (this.uxChkCopyToFolder.Checked)
                {
                    this.CopyToSjSite(theme);
                }
                if (!this.IsUpdateMode)
                {
                    this.uxThemeName.Text = string.Empty;
                    this.LoadDefaultForCreate();
                    this.ShowMessage("Theme created successfully.");
                }
                else 
                {
                    this.ShowMessage("Theme updated successfully.");
                }
                break;
            case PostBackAction.ChangeMode:
                if (this.IsUpdateMode)
                {
                    TaxThemeInfoCollection themeList = this.CurrentThemeList;
                    this.uxThemeList.Visible = true;
                    this.uxThemeName.Visible = false;
                    this.uxThemeList.DataSource = themeList;
                    this.uxThemeList.DataTextField = "ThemeName";
                    this.uxThemeList.DataValueField = "ThemeName";
                    this.uxThemeList.DataBind();
                    RadComboBoxItem currentTheme = this.uxThemeList.FindItemByValue(this.Page.Theme);
                    if (currentTheme != null)
                    {
                        this.uxThemeList.SelectedValue = currentTheme.Value;
                    }
                    else
                    {
                        this.uxThemeList.SelectedIndex = 0;
                    }
                    if (themeList.Count > 0)
                    {
                        this.CurrentEditTheme = this.FindThemeByName(this.uxThemeList.SelectedValue);
                    }                   
                }
                else
                {
                    this.uxThemeList.Visible = false;
                    this.uxThemeName.Visible = true;
                    this.LoadDefaultForCreate();
                }
                this.SetPanelOption();
                break;
            case PostBackAction.ChangeThemeName:
                this.SetPanelOption();
                this.CurrentEditTheme = this.FindThemeByName(this.uxThemeList.SelectedValue);
                break;
        }
    }  
    protected void OnDataBindControls(Enum type, object sender)
    {
        switch ((DataBindAction)type)
        {
            case DataBindAction.LoadDefaultForCreate:
                LoadDefaultForCreate();
                break;
            case DataBindAction.BindValidateItem:
                if (!this.IsUpdateMode)
                {
                    BasicValidationItem item = new BasicValidationItem
                    {
                        Rule = ValidationRule.Required,
                        Message = "Logo Image: This is a required field.",
                        ControlToValidateID = this.uxLogoImage.ID
                    };
                    this.uxValdator.Items.Add(item);
                }
                break;
        }

    }   

    protected void uxSubmit_Click(object sender, EventArgs e)
    {
        this.OnPostBackActions(PostBackAction.Submit, sender);
    }
    protected void ChangeFormMode(object sender, EventArgs e)
    {
        OnPostBackActions(PostBackAction.ChangeMode, sender);
    }
    protected void uxThemeList_SelectedIndexChanged(object sender, RadComboBoxSelectedIndexChangedEventArgs e)
    {
        this.OnPostBackActions(PostBackAction.ChangeThemeName, sender);
    }
   
    protected void SaveThemeInfomation(TaxThemeInformation theme)
    {
        string xmlFilePath = Server.MapPath(THEME_LIST_PATH);
        TaxThemeInfoCollection themeList = this.ThemeList;
        themeList.AddOrUpdate(theme);
        string xmlThemes = HSMCommon.ConvertObjectToXML(themeList, typeof(TaxThemeInfoCollection));
        TaxIOExtensions.WriteTextFile(xmlFilePath, new StringBuilder(xmlThemes));
    }    
    protected void LoadDefaultForCreate()
    {      
        string defaultThemeName = string.Format(THEME_NAME_DEFAULT_FOR_CREATE, HSMSessionManager.CurrentClientID);
        TaxThemeInformation theme = this.FindThemeByName(defaultThemeName);
        if (theme != null)
            this.CurrentEditTheme = theme;
    }
    protected void SetPanelOption()
    {
        string defaultTheme = string.Format(THEME_NAME_DEFAULT_FOR_CREATE, HSMSessionManager.CurrentClientID);
        if (this.IsUpdateMode && this.uxThemeList.SelectedValue.Equals(defaultTheme))
        {
            this.uxPanelOption.Visible = false;
            this.uxChkCopyToFolder.Checked = this.uxChkGenerate.Checked = false;
            this.uxChkSaveTheme.Checked = true;
        }
        else
        {
            this.uxPanelOption.Visible = true;
            this.uxChkCopyToFolder.Checked = this.uxChkGenerate.Checked = true;
            this.uxChkSaveTheme.Checked = true;
        }
    }
    protected TaxThemeInformation FindThemeByName(string themeName)
    {
        TaxThemeInfoCollection themeList = this.ThemeList;
        foreach (TaxThemeInformation theme in themeList)
        {
            if (theme.ThemeName.Equals(themeName, StringComparison.OrdinalIgnoreCase))
            {
                return theme;
            }
        }
        return null;
    }

    protected void GenerateTheme(TaxThemeInformation theme)
    {
        string sourcePath = Server.MapPath(TEMPALTE_PATH);
        string destPath = Server.MapPath(string.Format(THEME_PATH, theme.ThemeName));

        IThemeGenerator generator = new TaxThemeGenerator(theme, sourcePath, destPath);
        generator.Generate();
    }

    protected bool Validate()
    {
        if (!ValidateThemeName(this.uxThemeName.Text.Trim()))
            return false;
        
        // Validate Logo Image
        if (this.uxLogoImage.UploadedFiles.Count <= 0 && !this.IsUpdateMode)
        {
            this.ShowMessage("Logo Image: This is a required field.");
            return false;
        }
        else if (this.uxLogoImage.UploadedFiles.Count > 0)
        {
            if (!ValidateUploadFile(this.uxLogoImage, 542, 70, "Logo Image"))
                return false;
        }

        // Validate Background Image
        if (this.uxBackgroundImage.UploadedFiles.Count > 0)
        {
            if (!ValidateUploadFile(this.uxBackgroundImage, 640, 500, "Background Image"))
                return false;
        }
        return true;
    }
    protected bool ValidateUploadFile(RadUpload radUpload, int width, int height, string label)
    {
        string extension = ".png,.jpg,.bmp";
        UploadedFile upFile = radUpload.UploadedFiles[0];
        int maxImageSizeInByte = MAX_IMAGE_SIZE * 1024;

        if (!extension.Contains(upFile.GetExtension().ToLower()))
        {
            this.ShowMessage(string.Format("{0}: The uploaded image must be {1} file.", label, extension));
            return false;
        }

        if (upFile.ContentLength > maxImageSizeInByte)
        {
            this.ShowMessage(string.Format("{0}: File exceeds {1} KB.", label, MAX_IMAGE_SIZE));
            return false;
        }
        else
        {
            Image image = Image.FromStream(upFile.InputStream);
            if (image.Width > width || image.Height > height)
            {
                this.ShowMessage(string.Format("{0}: The uploaded image must be {1} x {2} pixels (width by height).", label, width, height));
                return false;
            }
        }
        return true;

    }   
    protected bool ValidateThemeName(string themeName)
    {
        if (!this.IsUpdateMode)
        {
            string appThemeDir = Server.MapPath(string.Format(THEME_PATH, string.Empty));
            themeName = Server.MapPath(string.Format(THEME_PATH, themeName));
            string[] themes = Directory.GetDirectories(appThemeDir);
            foreach (string folder in themes)
            {
                if (folder.Equals(themeName, StringComparison.OrdinalIgnoreCase))
                {
                    this.ShowMessage("The theme name already exists.");
                    return false;
                }
            }
        }        
        return true;
    }
    protected void ShowMessage(string message)
    {
        ClientScript.RegisterStartupScript(this.GetType(), "myScript", string.Format("DoAlert('{0}');", message), true);
    }

    protected void CopyToSjSite(TaxThemeInformation theme)
    {        
        string sourcePath = Server.MapPath(string.Format(THEME_PATH, theme.ThemeName));
        string currentDir = Path.Combine(Path.GetDirectoryName(Server.MapPath("~")), this.uxSJPath.Text.Trim());
        string destPath = Path.Combine(currentDir, string.Format("App_Themes\\{0}", theme.ThemeName));

        try
        {
            TaxIOExtensions.CopyDirectory(sourcePath, destPath);
        }
        catch
        {
            this.ShowMessage(string.Format("Cannot copy the theme to {0}", destPath));
        }
    }
    
}

